package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.service.UserService
import cn.xxstudy.blog.util.md5Code
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import javax.servlet.http.HttpSession

/**
 * 作者：xinxi on 2020/11/24 23:03
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO：一句话描述
 */
@Controller
@RequestMapping("/admin")
class LoginController {
    companion object {
        private const val admin = "admin/manager-login"
        private const val adminIndex = "admin/manager-index"
    }

    @Autowired
    private lateinit var service: UserService

    @GetMapping
    fun getAdmin(): String {
        return admin
    }

    @PostMapping("/login")
    fun login(@RequestParam user: String, @RequestParam pwd: String, model: Model, session: HttpSession, attributes: RedirectAttributes): String {
        val userInfo = service.login(user, md5Code(pwd) ?: "")
        if (userInfo != null) {
            userInfo.password = null
            model.addAttribute("user", userInfo)
            session.setAttribute("user", userInfo)
            return adminIndex
        }
        attributes.addFlashAttribute("response", "用户名或密码错误")
        return "redirect:/admin"
    }

    @GetMapping("/loginOut")
    fun loginOut(session: HttpSession): String {
        session.removeAttribute("user")
        return "redirect:/admin"
    }
}